package com.roads.supervisor.controller;

import com.roads.common.annotation.Log;
import com.roads.common.constant.Constants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.page.TableDataInfo;
import com.roads.common.enums.BusinessType;
import com.roads.common.utils.StringUtils;
import com.roads.project.domain.ProInstitutionDetail;
import com.roads.project.service.IProInstitutionService;
import com.roads.supervisor.domain.SupBoq;
import com.roads.supervisor.domain.SupMeterageDetailConstruction;
import com.roads.supervisor.domain.SupMeterageDetailDefect;
import com.roads.supervisor.domain.SupMeterageDetailOther;
import com.roads.supervisor.domain.SupMeterageDetailWinter;
import com.roads.supervisor.domain.SupMeterageMaster;
import com.roads.supervisor.domain.SupPeriod;
import com.roads.supervisor.service.ISupBoqService;
import com.roads.supervisor.service.ISupMeterageDetailService;
import com.roads.supervisor.service.ISupMeterageMasterService;
import com.roads.supervisor.service.ISupPeriodService;
import com.roads.workflow.domain.WorkflowTaskNode;
import com.roads.workflow.service.IWorkflowTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * @ClassName EngMeterageDetailController
 * @Description 监理计量详情controller
 * @Author nhp
 * @Date 2022/7/12 0012 15:57
 * @Version 1.0.0
 **/
@RestController
@RequestMapping("/supervisor/meterage/detail")
public class SupMeterageDetailController extends BaseController {

    @Autowired
    private ISupMeterageDetailService detailService;

    @Autowired
    private ISupMeterageMasterService masterService;

    @Autowired
    private ISupPeriodService periodService;

    @Autowired
    private ISupBoqService boqService;

    @Autowired
    private IWorkflowTaskService taskService;

    @Autowired
    private IProInstitutionService institutionService;

    /**
     * 获取用户节点列表
     *
     * @param masterId 主键ID
     * @return 结果
     */
    @GetMapping(value = "/selectUserOptions/{masterId}")
    public AjaxResult selectUserOptions(@PathVariable("masterId") Long masterId) {
        AjaxResult result = new AjaxResult();
        SupMeterageMaster master = masterService.getModelById(masterId);
        List<WorkflowTaskNode> nodes = taskService.selectUserOptions(master.getUuid());
        result.put("currentUser", master.getCurrentUser());
        result.put("nodes", nodes);
        return result;
    }

    /**
     * 查询监理计量-施工期列表
     *
     * @param model 施工期
     * @return 结果
     */
    @GetMapping("/listDetailConstruction")
    public TableDataInfo listDetailConstruction(SupMeterageDetailConstruction model) {
        startPage();
        List<SupMeterageDetailConstruction> list = detailService.selectConstructionList(model);
        return getDataTable(list);
    }

    /**
     * 查询施工期合同清单
     *
     * @param model 施工期
     * @return 结果
     */
    @GetMapping("/selectConstructionList")
    public TableDataInfo selectConstructionList(SupMeterageDetailConstruction model) {
        SupMeterageMaster master = masterService.getModelById(model.getMasterId());
        SupPeriod period = periodService.getModelByPeriodName(master.getInstitutionCode(), master.getPeriodName());
        SupBoq search = new SupBoq();
        search.setId(Integer.parseInt(String.valueOf(model.getMasterId())));
        search.setInstitutionCode(master.getInstitutionCode());
        search.setTemplateCode(period.getTemplateCode());
        search.setBoqType(Constants.SUPERVISION_BOQ_TYPE_CONSTRUCTION);
        search.setCreateBy(getUsername());
        startPage();
        List<SupBoq> list = boqService.selectBoqListByMeterage(search);
        return getDataTable(list);
    }


    /**
     * 批量新增施工期清单
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:add')")
    @Log(title = "监理计量-施工期", businessType = BusinessType.INSERT)
    @PostMapping("/saveDetailConstruction")
    public AjaxResult saveDetailConstruction(Long masterId, String ids) {
        return toAjax(detailService.saveDetailConstruction(masterId, ids));
    }

    /**
     * 获取监理计量-施工期清单详细信息
     */
    @GetMapping(value = "/getDetailConstruction/{id}")
    public AjaxResult getDetailConstruction(@PathVariable("id") Long id) {
        return AjaxResult.success(detailService.getDetailConstructionById(id));
    }

    /**
     * 修改监理计量-施工期详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:edit')")
    @Log(title = "监理计量-施工期", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDetailConstruction")
    public AjaxResult updateDetailConstruction(@RequestBody SupMeterageDetailConstruction model) {
        // 超计量控制
        SupMeterageMaster master = masterService.getModelById(model.getMasterId());
        ProInstitutionDetail bidDetail = institutionService.getDetailModelByInnerCode(master.getInstitutionCode());
        // 是否可以超计量
        String ultraMeasure = bidDetail.getUltraMeasure();
        // 不允许超计量
        if (Constants.NO.equals(ultraMeasure)) {
            SupBoq supBoq = boqService.getModelByInstitutionBoqCode(model.getInstitutionBoqCode());
            BigDecimal contractPeriodAmount = supBoq.getPeriodAmount() == null ? new BigDecimal(0) : supBoq.getPeriodAmount();
            // 查询修改前的值
            SupMeterageDetailConstruction beforeUpdateDetail = detailService.getDetailConstructionById(model.getId());
            BigDecimal oldPeriodAmount = beforeUpdateDetail.getPeriodAmount() == null ? new BigDecimal(0) : beforeUpdateDetail.getPeriodAmount();
            // 修改值
            BigDecimal periodAmount = model.getPeriodAmount() == null ? new BigDecimal(0) : model.getPeriodAmount();
            // 剩余工期
            BigDecimal remainderAmount = supBoq.getRemainderAmount() == null ? new BigDecimal(0) : supBoq.getRemainderAmount();
            // 剩余数量需要加上修改前的值
            remainderAmount = remainderAmount.add(oldPeriodAmount);
            // 本次填写数量，大于剩余数量
            if (periodAmount.compareTo(remainderAmount) == 1) {
                BigDecimal alreadyAmount = supBoq.getAlreadyAmount() == null ? new BigDecimal(0) : supBoq.getAlreadyAmount();
                String errorMessage = model.getBoqCode()
                        + "合同期数为：" + contractPeriodAmount.stripTrailingZeros().toPlainString()
                        + "，已计量数量为：" + alreadyAmount.subtract(oldPeriodAmount).stripTrailingZeros().toPlainString()
                        + "，剩余数量为：" + remainderAmount.add(oldPeriodAmount).stripTrailingZeros().toPlainString();
                return error(errorMessage);
            }
        }
        return toAjax(detailService.updateDetailConstruction(model));
    }

    /**
     * 删除监理计量-施工期详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:remove')")
    @Log(title = "监理计量-施工期", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteDetailConstruction/{ids}")
    public AjaxResult deleteDetailConstruction(@PathVariable Long[] ids) {
        if (StringUtils.isNull(ids) || ids.length == 0) {
            return error("请选择要删除的数据");
        }
        return toAjax(detailService.deleteDetailConstruction(ids));
    }

    /**
     * 查询监理计量-冬休期列表
     */
    @GetMapping("/listDetailWinter")
    public TableDataInfo listDetailWinter(SupMeterageDetailWinter model) {
        startPage();
        List<SupMeterageDetailWinter> list = detailService.selectWinterList(model);
        return getDataTable(list);
    }

    /**
     * 查询冬休期合同清单
     *
     * @param model 冬休期
     * @return 结果
     */
    @GetMapping("/selectWinterList")
    public TableDataInfo selectWinterList(SupMeterageDetailWinter model) {
        SupMeterageMaster master = masterService.getModelById(model.getMasterId());
        SupPeriod period = periodService.getModelByPeriodName(master.getInstitutionCode(), master.getPeriodName());
        SupBoq search = new SupBoq();
        search.setId(Integer.parseInt(String.valueOf(model.getMasterId())));
        search.setInstitutionCode(master.getInstitutionCode());
        search.setTemplateCode(period.getTemplateCode());
        search.setBoqType(Constants.SUPERVISION_BOQ_TYPE_WINTER);
        search.setCreateBy(getUsername());
        startPage();
        List<SupBoq> list = boqService.selectBoqListByMeterage(search);
        return getDataTable(list);
    }

    /**
     * 批量新增冬休期清单
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:add')")
    @Log(title = "监理计量-冬休期", businessType = BusinessType.INSERT)
    @PostMapping("/saveDetailWinter")
    public AjaxResult saveDetailWinter(Long masterId, String ids) {
        return toAjax(detailService.saveDetailWinter(masterId, ids));
    }

    /**
     * 获取监理计量-冬休期清单详细信息
     */
    @GetMapping(value = "/getDetailWinter/{id}")
    public AjaxResult getDetailWinter(@PathVariable("id") Long id) {
        return AjaxResult.success(detailService.getDetailWinterById(id));
    }

    /**
     * 修改监理计量-冬休期详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:edit')")
    @Log(title = "监理计量-冬休期", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDetailWinter")
    public AjaxResult updateDetailWinter(@RequestBody SupMeterageDetailWinter model) {
        // 超计量控制
        SupMeterageMaster master = masterService.getModelById(model.getMasterId());
        ProInstitutionDetail bidDetail = institutionService.getDetailModelByInnerCode(master.getInstitutionCode());
        // 是否可以超计量
        String ultraMeasure = bidDetail.getUltraMeasure();
        // 不允许超计量
        if (Constants.NO.equals(ultraMeasure)) {
            SupBoq supBoq = boqService.getModelByInstitutionBoqCode(model.getInstitutionBoqCode());
            BigDecimal contractPeriodAmount = supBoq.getPeriodAmount() == null ? new BigDecimal(0) : supBoq.getPeriodAmount();
            // 查询修改前的值
            SupMeterageDetailWinter beforeUpdateDetail = detailService.getDetailWinterById(model.getId());
            BigDecimal oldPeriodAmount = beforeUpdateDetail.getPeriodAmount() == null ? new BigDecimal(0) : beforeUpdateDetail.getPeriodAmount();
            // 修改值
            BigDecimal periodAmount = model.getPeriodAmount() == null ? new BigDecimal(0) : model.getPeriodAmount();
            // 剩余工期
            BigDecimal remainderAmount = supBoq.getRemainderAmount() == null ? new BigDecimal(0) : supBoq.getRemainderAmount();
            // 剩余数量需要加上修改前的值
            remainderAmount = remainderAmount.add(oldPeriodAmount);
            // 本次填写数量，大于剩余数量
            if (periodAmount.compareTo(remainderAmount) == 1) {
                BigDecimal alreadyAmount = supBoq.getAlreadyAmount() == null ? new BigDecimal(0) : supBoq.getAlreadyAmount();
                String errorMessage = model.getBoqCode()
                        + "合同期数为：" + contractPeriodAmount.stripTrailingZeros().toPlainString()
                        + "，已计量数量为：" + alreadyAmount.subtract(oldPeriodAmount).stripTrailingZeros().toPlainString()
                        + "，剩余数量为：" + remainderAmount.add(oldPeriodAmount).stripTrailingZeros().toPlainString();
                return error(errorMessage);
            }
        }
        return toAjax(detailService.updateDetailWinter(model));
    }

    /**
     * 删除监理计量-冬休期详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:remove')")
    @Log(title = "监理计量-冬休期", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteDetailWinter/{ids}")
    public AjaxResult deleteDetailWinter(@PathVariable Long[] ids) {
        if (StringUtils.isNull(ids) || ids.length == 0) {
            return error("请选择要删除的数据");
        }
        return toAjax(detailService.deleteDetailWinter(ids));
    }

    /**
     * 查询监理计量-缺陷责任期列表
     */
    @GetMapping("/listDetailDefect")
    public TableDataInfo listDetailDefect(SupMeterageDetailDefect model) {
        startPage();
        List<SupMeterageDetailDefect> list = detailService.selectDefectList(model);
        return getDataTable(list);
    }

    /**
     * 查询缺陷责任期合同清单
     *
     * @param model 缺陷责任期
     * @return 结果
     */
    @GetMapping("/selectDefectList")
    public TableDataInfo selectDefectList(SupMeterageDetailDefect model) {
        SupMeterageMaster master = masterService.getModelById(model.getMasterId());
        SupPeriod period = periodService.getModelByPeriodName(master.getInstitutionCode(), master.getPeriodName());
        SupBoq search = new SupBoq();
        search.setId(Integer.parseInt(String.valueOf(model.getMasterId())));
        search.setInstitutionCode(master.getInstitutionCode());
        search.setTemplateCode(period.getTemplateCode());
        search.setBoqType(Constants.SUPERVISION_BOQ_TYPE_DEFECT);
        search.setCreateBy(getUsername());
        startPage();
        List<SupBoq> list = boqService.selectBoqListByMeterage(search);
        return getDataTable(list);
    }

    /**
     * 批量新增缺陷责任期清单
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:add')")
    @Log(title = "监理计量-缺陷责任期", businessType = BusinessType.INSERT)
    @PostMapping("/saveDetailDefect")
    public AjaxResult saveDetailDefect(Long masterId, String ids) {
        return toAjax(detailService.saveDetailDefect(masterId, ids));
    }

    /**
     * 获取监理计量-缺陷责任期清单详细信息
     */
    @GetMapping(value = "/getDetailDefect/{id}")
    public AjaxResult getDetailDefect(@PathVariable("id") Long id) {
        return AjaxResult.success(detailService.getDetailDefectById(id));
    }

    /**
     * 修改监理计量-缺陷责任期详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:edit')")
    @Log(title = "监理计量-缺陷责任期", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDetailDefect")
    public AjaxResult updateDetailDefect(@RequestBody SupMeterageDetailDefect model) {
        // 超计量控制
        SupMeterageMaster master = masterService.getModelById(model.getMasterId());
        ProInstitutionDetail bidDetail = institutionService.getDetailModelByInnerCode(master.getInstitutionCode());
        // 是否可以超计量
        String ultraMeasure = bidDetail.getUltraMeasure();
        // 不允许超计量
        if (Constants.NO.equals(ultraMeasure)) {
            SupBoq supBoq = boqService.getModelByInstitutionBoqCode(model.getInstitutionBoqCode());
            BigDecimal contractPeriodAmount = supBoq.getPeriodAmount() == null ? new BigDecimal(0) : supBoq.getPeriodAmount();
            // 查询修改前的值
            SupMeterageDetailDefect beforeUpdateDetail = detailService.getDetailDefectById(model.getId());
            BigDecimal oldPeriodAmount = beforeUpdateDetail.getPeriodAmount() == null ? new BigDecimal(0) : beforeUpdateDetail.getPeriodAmount();
            // 修改值
            BigDecimal periodAmount = model.getPeriodAmount() == null ? new BigDecimal(0) : model.getPeriodAmount();
            // 剩余工期
            BigDecimal remainderAmount = supBoq.getRemainderAmount() == null ? new BigDecimal(0) : supBoq.getRemainderAmount();
            // 剩余数量需要加上修改前的值
            remainderAmount = remainderAmount.add(oldPeriodAmount);
            // 本次填写数量，大于剩余数量
            if (periodAmount.compareTo(remainderAmount) == 1) {
                BigDecimal alreadyAmount = supBoq.getAlreadyAmount() == null ? new BigDecimal(0) : supBoq.getAlreadyAmount();
                String errorMessage = model.getBoqCode()
                        + "合同期数为：" + contractPeriodAmount.stripTrailingZeros().toPlainString()
                        + "，已计量数量为：" + alreadyAmount.subtract(oldPeriodAmount).stripTrailingZeros().toPlainString()
                        + "，剩余数量为：" + remainderAmount.add(oldPeriodAmount).stripTrailingZeros().toPlainString();
                return error(errorMessage);
            }
        }
        return toAjax(detailService.updateDetailDefect(model));
    }

    /**
     * 删除监理计量-缺陷责任期详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:remove')")
    @Log(title = "监理计量-缺陷责任期", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteDetailDefect/{ids}")
    public AjaxResult deleteDetailDefect(@PathVariable Long[] ids) {
        if (StringUtils.isNull(ids) || ids.length == 0) {
            return error("请选择要删除的数据");
        }
        return toAjax(detailService.deleteDetailDefect(ids));
    }

    /**
     * 查询监理计量-其他支付项目列表
     *
     * @param model 施工期
     * @return 结果
     */
    @GetMapping("/listDetailOther")
    public TableDataInfo listDetailConstruction(SupMeterageDetailOther model) {
        startPage();
        List<SupMeterageDetailOther> list = detailService.selectOtherList(model);
        return getDataTable(list);
    }

    /**
     * 同步其他支付项目固定值
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:add')")
    @Log(title = "监理计量-其他", businessType = BusinessType.INSERT)
    @GetMapping(value = "/syncDetailOtherItem/{masterId}")
    public AjaxResult syncDetailOtherItem(@PathVariable("masterId") Long masterId) {
        return toAjax(detailService.syncDetailOtherItem(masterId));
    }

    /**
     * 获取监理计量-其他支付项目详细信息
     */
    @GetMapping(value = "/getDetailOther/{id}")
    public AjaxResult getDetailOther(@PathVariable("id") Long id) {
        return AjaxResult.success(detailService.getDetailOtherById(id));
    }

    /**
     * 修改监理计量-其他支付项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:detail:edit')")
    @Log(title = "监理计量-其他", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDetailOther")
    public AjaxResult updateDetailOther(@RequestBody SupMeterageDetailOther model) {
        return toAjax(detailService.updateDetailOther(model));
    }

}
